<template>
  <login-form v-if="$store.state.mobile.userAgent==='mobile'"></login-form>
  <div class="login" v-else>
      <div class="login-weaper  animated bounceInDown">
      <div class="login-logo">
        <img :src="loginConfig.loginUrl" alt="">
      </div>
      <p class="login-tip">{{loginConfig.loginName}}</p>
      <div class="login-border">
        <div class="login-main">
          <h4 class="login-title">
            <!-- qiankun微前端，适配共享交换，不展示租户下拉框 -->
            <el-select v-model="active"
                       class="login-select animated fadeIn"
                       placeholder="点击请选择租户"
                       @change="handleCommand"
                       v-if="!isQiankun">
              <el-option v-for="(item) in tenantList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </h4>
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form-content">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" style="color: #409eff"/>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" :type="passwordType" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
                <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" style="color: #409eff"/>
                <i slot="suffix" class="el-icon-view" @click="showPassword" />
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <Verify
                @success="verifySuccess"
                :mode="'pop'"
                :captchaType="'blockPuzzle'"
                :imgSize="{ width: '330px', height: '155px' }"
                ref="verify"
              />
            </el-form-item>
            <el-form-item style="width:100%;">
              <el-button  size="medium" type="primary" style="width:100%;margin:30px 0" @click.native.prevent="handleLogin">
                登 录
              </el-button>
            </el-form-item>
          </el-form>
        </div>

      </div>
    </div>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>{{loginConfig.copyrightInfo}}</span>
    </div>
  </div>
</template>

<script>
import loginForm from '@/views/custom/mobiledesign/mobileComponents/loginForm.vue'
import { getTenantIdByName } from "@/api/system/tenant";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getTenantEnable } from "@/utils/admin";
import { getStore, setStore } from '@/utils/store'
import Verify from "@/components/verifition/Verify";
import {getAccessToken, getRefreshToken, getTenantId, setToken, encryption} from '@/utils/auth'
import {getHomePage} from '@/api/login'
import { getVerifyCaptcha } from "@/api/system/systemConfig";
import { getQiankunEnv } from "@/utils/micro";

export default {
  name: "Login",
  components: {
    Verify,
    loginForm
  },
  data() {
    return {
      active:'',
      codeUrl: "",
      captchaEnable: true,
      tenantEnable: true,
      tenantList: [],
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: "",
        tenantId: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
      },
      redirect: undefined,
      passwordType: "password",
      loginConfig: {

      },
      isQiankun: getQiankunEnv()
    };
  },
  created() {
    // 租户开关
    this.tenantEnable = getTenantEnable();
    // 设置租户
    this.active = getStore({ name: 'tenantId' })
    // 重定向地址
    this.redirect = this.$route.query.redirect;
    this.getCookie();
    this.getTenantId();
    this.getLoginData()
  },
  methods: {
     getLoginData() {
      this.$store.dispatch('GetLoginConf').then(() => {
           this.loginConfig = this.$store.state.user && this.$store.state.user.loginConfigData
           document.title = this.$store.state.user && this.$store.state.user.loginConfigData.loginName
            var link = document.querySelector("link[rel*='icon']") || document.createElement('link')
            link.type = 'image/x-icon'
            link.rel = 'shortcut icon'
            link.href = this.$store.state.user.loginConfigData.browserUrl
            document.getElementsByTagName('head')[0].appendChild(link)
        })
    },
    getTenantId() {
      getTenantIdByName().then((res) => {
        this.tenantList = res.data
      })
    },
     showPassword() {
      this.passwordType == ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    handleCommand (command) {
      // 切换租户清空 账号 密码
      this.loginForm.username = ''
      this.loginForm.password = ''
      setStore({ name: 'tenantId', content: command })
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const tenantName = Cookies.get('tenantName');
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        tenantName: tenantName === undefined ? this.loginForm.tenantName : tenantName,
      };
    },
    handleLogin() {
      getVerifyCaptcha().then((res) => {
        if(res.code === 0){
            if(res.data){
               this.$refs.loginForm.validate(valid => {
                if (valid) {
                  this.$refs.verify.show();
                }
              });
            }else{
                this.verifySuccess('')
            }
        }
      })
    },
    verifySuccess(params) {
      this.loginForm.code = params.captchaVerification;
      this.loginForm.tenantId = this.active ? this.active : this.tenantList[0] && this.tenantList[0].id
      let password = encryption(this.loginForm.password)  //密码加密
      setStore({ name: 'tenantId', content: this.loginForm.tenantId  })

      // 设置 Cookie
      // if (this.loginForm.rememberMe) {
      //   Cookies.set("username", this.loginForm.username, { expires: 30 });
      //   Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
      //   Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
      //   Cookies.set('tenantName', this.loginForm.tenantName, { expires: 30 });
      // } else {
      //   Cookies.remove("username");
      //   Cookies.remove("password");
      //   Cookies.remove('rememberMe');
      //   Cookies.remove('tenantName');
      // }
      // 发起登陆
      const data = {
        code: this.loginForm.code,
        password: password,
        tenantId: this.loginForm.tenantId,
        tenantName: '',
        username: this.loginForm.username
      }
      window.localStorage.setItem('TENANT_ID',this.loginForm.tenantId)
      this.$store.dispatch("Login", data).then(() => {
        // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
        getHomePage().then(res => {
          if (this.isQiankun && process.env.VUE_APP_NEW_HOME_URL) {
            // qiankun微前端，适配共享交换，登录后跳转到共享交换首页
            this.$router.push({ path: process.env.VUE_APP_NEW_HOME_URL }).catch(()=>{});
          } else {
            this.$router.push({ path: res.data.path }).catch(()=>{});
          }
        }).catch(error => {
          localStorage.clear();
          console.log(error)
        })

        this.$websocket.initWebSocket(getAccessToken())
      }).catch(() => {
      });
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
@-webkit-keyframes animate-cloud {
  from {
    background-position: 600px 100%;
  }
  to {
    background-position: 0 100%;
  }
}
@-moz-keyframes animate-cloud {
  from {
    background-position: 600px 100%;
  }
  to {
    background-position: 0 100%;
  }
}
@-ms-keyframes animate-cloud {
  from {
    background-position: 600px 100%;
  }
  to {
    background-position: 0 100%;
  }
}
@-o-keyframes animate-cloud {
  from {
    background-position: 600px 100%;
  }
  to {
    background-position: 0 100%;
  }
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login.png");
  background-size: cover;
  animation: animate-cloud 20s linear infinite;
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #999;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-tip {
  color: #409eff;
  text-align: center;
  font-weight: 700;
  font-size: 16px;
}

.login-logo {
  overflow: hidden;
  width: 110px;
  height: 110px;
  margin: -50px auto 20px auto;
  border-radius: 50%;
  -webkit-box-shadow: 0 4px 40px rgba(0, 0, 0, 0.07);
  box-shadow: 0 4px 40px rgba(0, 0, 0, 0.07);
  padding: 10px;
  background-color: #fff;
  z-index: 1;
  position: relative;
  box-sizing: border-box;
  padding: 20px;

  img {
    width: 100%;
    height: 100%;
  }
}
.login-weaper {
  position: relative;
  margin: 0 auto;
  width: 380px;
  padding: 0 40px;
  box-sizing: border-box;
  box-shadow: 0 7px 25px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  border-radius: 3px;
}

.login-border {
  border-left: none;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  color: #fff;
  background-color: #fff;
  width: 100%;
  float: left;
  box-sizing: border-box;
}

.login-main {
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.login-main > h3 {
  margin-bottom: 20px;
}

.login-main > p {
  color: #76838f;
}

.login-title {
  color: #333;
  margin-bottom: 30px;
  font-weight: 500;
  font-size: 22px;
  text-align: center;
  letter-spacing: 4px;
}

.login-select {
  input {
    color: #333;
    font-size: 14px;
    font-weight: 400;
    border: none;
    text-align: center;
  }
}

.login-form-content {
  margin: 10px 0;

  i {
    color: #409eff;
  }

  .el-form-item__content {
    width: 100%;
  }

  .el-form-item {
    margin-bottom: 12px;
  }

  .el-input {
    input {
      padding-bottom: 10px;
      text-indent: 15px;
      background: transparent;
      border: none;
      border-radius: 0;
      color: #333;
      border-bottom: 1px solid rgb(235, 237, 242);
    }

    .el-input__prefix {
      i {
        padding: 0 5px;
        font-weight: 600;
        font-size: 18px !important;
      }
    }
  }
}

</style>
